<template>
  <div>
    <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px">
      <el-form-item label="修改原因：" prop="title" label-width="100px">
        <el-input v-model="formData.title" />
      </el-form-item>
      <el-form-item label="施工台账：" label-width="100px">
        <el-table ref="dataTableRef" v-loading="loading" :data="contractItems" height="30vh">
          <el-table-column label="材料类型" align="center" width="100">
            <template #default="scope">
              <el-select
                v-if="!scope.row.id"
                v-model="scope.row.itemType"
                size="small"
                placeholder="请选择"
              >
                <el-option
                  v-for="key in Object.keys(SaleMealTypeLabel)"
                  :key="key"
                  :label="SaleMealTypeLabel[key]"
                  :value="key"
                />
              </el-select>
              <span v-else>{{ SaleMealTypeLabel[scope.row.itemType] }}</span>
            </template>
          </el-table-column>
          <el-table-column label="材料名称" prop="resourceId" width="200">
            <template #default="scope">
              <el-select
                v-if="!scope.row.id"
                v-model="scope.row.resourceId"
                size="small"
                placeholder="请输入"
                filterable
                remote
                remote-show-suffix
                clearable
                :remote-method="(q) => remoteMethodMeal(q, scope.row.itemType)"
                :loading="remoteLoading"
                @change="(val) => changeMeal(val, scope)"
              >
                <el-option v-for="m in mealOpts" :key="m.id" :label="m.name" :value="m.id!" />
              </el-select>
              <span v-else>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column label="规格" prop="spec" />
          <el-table-column label="单位" prop="unit" align="center" width="80" />
          <el-table-column label="数量" align="center" prop="quantity" width="100">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.quantity"
                size="small"
                style="width: 100%"
                :min="1"
                controls-position="right"
              />
            </template>
          </el-table-column>
          <el-table-column label="单价" align="center" prop="price" width="180">
            <template #default="scope">
              <el-input-number
                v-model="scope.row.price"
                size="small"
                :precision="2"
                :step="1"
                :min="0.01"
                style="width: 100%"
              >
                <template #prefix>
                  <span>￥</span>
                </template>
              </el-input-number>
            </template>
          </el-table-column>
          <el-table-column label="操作" fixed="right" width="100" align="center">
            <template #default="scope">
              <el-button
                v-if="scope.$index == contractItems.length - 1"
                size="small"
                type="primary"
                link
                @click="handleAddItem"
              >
                添加
              </el-button>
              <el-button size="small" type="danger" link @click="handleDeleteItem(scope.row)">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
    </el-form>
  </div>
</template>

<script lang="ts" setup>
import MaterialAPI, { MaterialPageVO, MaterialType } from "@/api/business/material/material.api";
import { SaleMealTypeLabel } from "@/api/business/material/sealMeal.api";
import { ContractItem } from "@/api/flow/contract.api";
import ContractLedgerAPI, { ContractLedgerForm } from "@/api/flow/contractLedger.api";
import { cloneDeep } from "lodash-es";

const props = defineProps<{
  id: string;
  data: ContractItem[];
}>();

const defaultForm = {
  contractId: "",
  title: "",
  items: [],
};
const loading = ref(false);
const remoteLoading = ref(false); //搜索材料loading
const formData = ref<ContractLedgerForm>(cloneDeep(defaultForm)); //表单数据
const contractItems = ref<ContractItem[]>([]); //合同材料列表
const mealOpts = ref<MaterialPageVO[]>([]); //备选-材料列表

const rules = reactive({
  title: [{ required: true, message: "请输入修改原因", trigger: "blur" }],
});

watch(
  () => props.data,
  (val) => {
    if (!val) {
      return;
    }
    contractItems.value = cloneDeep(val);
  },
  {
    immediate: true,
    deep: true,
  }
);

// 搜索材料备选
function remoteMethodMeal(query: string, type: MaterialType) {
  if (query) {
    remoteLoading.value = true;
    MaterialAPI.getPage({
      pageNum: 1,
      pageSize: 30,
      type,
      keywords: query,
    })
      .then((res) => {
        mealOpts.value = res.list;
      })
      .finally(() => {
        remoteLoading.value = false;
      });
  }
}

// 选择材料
function changeMeal(val: string, scope: any) {
  const meal = mealOpts.value.find((m) => m.id === val);
  if (meal) {
    scope.row.resourceId = val;
    scope.row.name = meal.name;
    scope.row.spec = meal.spec;
    scope.row.unit = meal.unit;
    scope.row.code = meal.code;
    scope.row.price = parseFloat(meal.price || "0");
    scope.row.remark = meal.remark;
  }
}

// 添加材料
function handleAddItem() {
  contractItems.value.push({
    itemType: "",
    name: "",
    quantity: 1,
    code: "",
  });
}

// 删除材料
function handleDeleteItem(item: ContractItem) {
  contractItems.value = contractItems.value.filter((i) => i.id !== item.id);
}

// 提交编辑
async function submit() {
  loading.value = true;
  // 处理数据
  try {
    formData.value.contractId = props.id;
    formData.value.items = contractItems.value;
    await ContractLedgerAPI.reviewContract(formData.value);
  } catch (error) {
    console.error("保存失败", error);
  }
  loading.value = false;
}

defineExpose({
  submit,
});
</script>

<style lang="scss" scoped></style>
